package client;

import etc.SynchronizationParameters;
import java.io.File;
import java.util.ArrayList;
import java.util.Observable;

public class MirrorRemoteOnLocalTask extends Observable implements Runnable {

	private SyncClient client = null;

	private ArrayList<String[]> filesToGet = null, filesToDelete = null;

	public MirrorRemoteOnLocalTask( SyncClient client, ArrayList<String[]> filesToGet, ArrayList<String[]> filesToDelete ) {
		this.client = client;
		this.filesToDelete = filesToDelete;
		this.filesToGet = filesToGet;
	}

	@Override
	public void run() {
		Integer completedTaskCount = 0;

		if( filesToDelete != null ) {
			for (String[] strings : filesToDelete) {
				String deleteResult = "Could not delete local file '"+strings[0]+"'.";

				try{
					File f = new File( SynchronizationParameters.getLocalPath() + "\\" + strings[0].replace('/', '\\') );
					if( (f!=null) && (f.exists()) ) {
						if( f.delete() ) {
							deleteResult = "Deleted local file '"+strings[0]+"'.";
						}
					}
					f = null;
				}catch(Exception e){}

				setChanged();
				notifyObservers( deleteResult );

				completedTaskCount++;
				setChanged();
				notifyObservers( completedTaskCount );

				try{
					Thread.sleep(10);
				}catch(InterruptedException ie){
					return;
				}
			}
		}

		if( filesToGet != null ) {
			while( filesToGet.size() > 0 ) {
				String[] currentFile = filesToGet.get( filesToGet.size() - 1 );
				filesToGet.remove( filesToGet.size() - 1 );

				String status = "Downloading file '"+currentFile[0]+"'.";
				setChanged();
				notifyObservers(status);

				String downloadResult = client.downloadFile( currentFile[0], Long.parseLong( currentFile[1] ) );

				setChanged();
				notifyObservers( downloadResult );

				completedTaskCount++;
				setChanged();
				notifyObservers( completedTaskCount );

				try{
					Thread.sleep(10);
				}catch(InterruptedException ie){
					return;
				}
			}
		}

		String finishedMessage = "SYNC_FINISHED";
		setChanged();
		notifyObservers( finishedMessage );
	}

}
